<?php

namespace App;

use App\Model;
use App\Topic;
use App\PostTopic;
use Illuminate\Database\Eloquent\Builder;
class Post extends Model
{
    protected $table = "posts";
   public function  user(){
       return $this->belongsTo('App\User','user_id','id');
   }

   public function comments(){
       return $this->hasMany('App\Comment')
           ->orderBy('created_at','desc');
   }

   public  function  zan($user_id){
       return $this->hasOne('App\Zan')->where('user_id',$user_id);
   }
   //一篇文章赞的个数
    public function zans(){
        return $this->hasMany('App\Zan');
    }


    /*
     * 一篇文章有哪些主题
     */
    public function topics()
    {
        return $this->belongsToMany(\App\Topic::class, 'post_topics', 'post_id', 'topic_id')->withPivot(['topic_id', 'post_id']);
    }

    public function postTopics()
    {
        return $this->hasMany(\App\PostTopic::class, 'post_id');
    }

    /**
     * @param Builder $query
     * @param $topic_id
     * @return Builder
     * 不属于某一个专题的文章
     */
    public function scopeTopicNotBy(Builder $query, $topic_id)
    {
        return $query->doesntHave('postTopics', 'and', function($q) use ($topic_id) {
            $q->where("topic_id", $topic_id);
        });
    }

    /**
     * @param $query
     * @param $user_id
     * @return mixed
     * 属于某一个作者的文章
     */
    public function scopeAuthorBy(Builder $query, $user_id)
    {
        return $query->where('user_id', $user_id);
    }

    /*
     * 可以显示的文章
     */
    public function scopeAviable(Builder $query)
    {
        return $query->whereIn('status', [0, 1]);
    }
}
